var knex = require('../dbhelper').instance();
var Promise = require('bluebird');
module.exports = {
    gettaskitem: function (params) {
        return new Promise(function (resolve, reject) {
            var number = params.tasknumber;
            // 事务模式
            knex.transaction(function (trx) {
                return Promise.all([
                        knex.raw('select count(1) as totalcount from ?? where status=1 and userid=?', [params.tablename, params.userid]).transacting(trx).then(function (data) {
                            console.log(data);
                            var rows = data[0][0].totalcount;
                            if (rows > 0) { //有数据，不分配任务
                                return Promise.all([
                                    knex.raw('update ?? a INNER JOIN (select resourceid from ?? where status=0  ORDER BY rand() limit ?) b on a.resourceid=b.resourceid set a.userid=?,status=1;', [params.tablename, params.tablename, rows > number ? 0 : Math.abs(number - rows), params.userid]).transacting(trx), //分配任务
                                    //knex.raw('select b.* from ?? a LEFT JOIN fileresource b on a.resourceid=b.resourceid where a.status=1 and a.userid=? limit ?', [params.tablename, params.userid, number]).transacting(trx) //返回任务
                                    knex.raw('select a.*,b.tasktags from ?? a LEFT JOIN tasklist b on b.dsid=? where a.status=1 and a.userid=? limit ?', [params.tablename, params.dsid, params.userid, number]).transacting(trx) //返回任务
                                ]);
                            } else {
                                return Promise.all([
                                    knex.raw('update ?? a INNER JOIN (select resourceid from ?? where status=0  ORDER BY rand() limit ?) b on a.resourceid=b.resourceid set a.userid=?,status=1;', [params.tablename, params.tablename, number, params.userid]).transacting(trx), //分配任务

                                    /* knex.raw('select a.* from ?? a where a.status=1 and a.userid=? limit ?', [params.tablename, params.userid, number]).transacting(trx) //返回任务 */
                                    knex.raw('select a.*,b.tasktags from ?? a LEFT JOIN tasklist b on b.dsid=? where a.status=1 and a.userid=? limit ?', [params.tablename, params.dsid, params.userid, number]).transacting(trx) //返回任务
                                ]);
                            }
                        })
                    ])
                    .then(trx.commit)
                    .catch(trx.rollback);
            }).then(function (trx) {
                resolve(trx);
            }).catch(function (err) {
                console.error(err);
                reject(err);
            });

        });
    },
    marksubmit: function (rows, params, currentflow) {
        currentflow = currentflow || 'mark';

        return new Promise(function (resolve, reject) {
            knex.transaction(function (trx) {
                return Promise.all([
                        //获取当前任务的流程配置信息
                        knex('flowconfig as a').leftJoin('tasklist as b', 'a.configid', 'b.configid').where('b.taskid', params.taskid).transacting(trx).then(function (config_data) {
                            var inspect = config_data[0].inspect;
                            var rndinspect = config_data[0].rndinspect;
                            var accept = config_data[0].accept;

                            var status = 2;

                            if (currentflow == 'mark') {
                                if (inspect == 1) { //检查启用
                                    status = 2; //进入待检查(下一流程状态)
                                } else if (rndinspect == 1) { //抽查启用
                                    status = 4; //进入待抽查(下一流程状态)
                                } else if (accept == 1) { //验收启用
                                    status = 6; //进入待验收下一流程状态)
                                }
                            } else if (currentflow == 'inspect') {
                                if (rndinspect == 1) { //抽查启用
                                    status = 4; //进入待抽查下一流程状态)
                                } else if (accept == 1) { //验收启用
                                    status = 6; //进入待验收下一流程状态)
                                }
                            } else if (currentflow == 'rndinspect') {
                                if (rndinspect == 1) { //验收启用
                                    if (accept == 1) { //验收启用
                                        status = 6; //进入待验收下一流程状态)
                                    } //status = 6; //进入待抽查下一流程状态)
                                }
                            }
                            var chunkSize = 10;
                            var promiseArray = [];
                            promiseArray.push(
                                knex.batchInsert('marklog', rows, chunkSize)
                                .transacting(trx));
                            rows.forEach(log => {
                                promiseArray.push(
                                    knex.raw('call proc_log_partition(?,?,?,?,?,?,?,now(),?)', [log.userid, log.resourceid, log.taskid, log.spent, (log.result == undefined ? '-1' : log.result), '', '', log.actions])
                                    .transacting(trx));
                            });

                            if (status == 2) {
                                if (params.selectedids.length > 0) {
                                    promiseArray.push(knex.raw('update ?? set status=2,label=?,userid=null where find_in_set (resourceid, ?)', [params.tablename, params.yes_label, params.selectedids.join(',')]).transacting(trx));
                                }
                                if (params.unselectedids.length > 0) {
                                    promiseArray.push(knex.raw('update ?? set status=2,label=?,userid=null where find_in_set (resourceid, ?)', [params.tablename, params.no_label, params.unselectedids.join(',')]).transacting(trx));
                                }
                            } else if (status == 4) {
                                if (params.selectedids.length > 0) { //驳回,退回至待标注状态
                                    promiseArray.push(knex.raw('update ?? set status=0,userid=null where find_in_set (resourceid, ?)', [params.tablename, params.selectedids.join(',')]).transacting(trx));
                                }
                                if (params.unselectedids.length > 0) { //检查通过
                                    if (params.actions == '1') { //标注引擎(1=数据清洗 2=单分类 3=多分类 4=多点标注 )
                                        promiseArray.push(knex.raw('update ?? set status=4,userid=null where find_in_set (resourceid, ?)', [params.tablename, params.unselectedids.join(',')]).transacting(trx));
                                    } else {
                                        promiseArray.push(knex.raw('update ?? set status=4,userid=null,label=? where find_in_set (resourceid, ?)', [params.tablename, params.yes_label, params.unselectedids.join(',')]).transacting(trx));
                                    }
                                }
                            } else if (status == 6) {
                                var pre_status = 0; //默认为待标注状态
                                if (currentflow == 'rndinspect') {
                                    if (inspect == 1) { //抽查的上一流程已经启用
                                        pre_status = 2; //抽查驳回至待检查
                                    } else {
                                        pre_status = 2; //抽查的上一次没有标注，直接回归源
                                    }
                                } else if (currentflow == 'inspect') {
                                    pre_status = 0; //检查的上一状态，为标注，回退则直接进入待标注库
                                }
                                if (params.selectedids.length > 0) { //驳回,退回至任务配置的上一次流程状态
                                    promiseArray.push(knex.raw('update ?? set status=?,userid=null where find_in_set (resourceid, ?)', [params.tablename, pre_status, params.selectedids.join(',')]).transacting(trx)); //抽查驳回
                                }
                                if (params.unselectedids.length > 0) { //检查通过
                                    promiseArray.push(knex.raw('update ?? set status=6,userid=null,label=?  where find_in_set (resourceid, ?)', [params.tablename, params.yes_label, params.unselectedids.join(',')]).transacting(trx)); //抽查通过
                                }
                                /* promiseArray.push(knex.raw('update ?? set status=?,userid=null where find_in_set (resourceid, ?)', [params.tablename, pre_status, params.selectedids.concat(params.unselectedids).join(',')]).transacting(trx)); //抽查驳回

                                promiseArray.push(knex.raw('update ?? set status=6,userid=null where find_in_set (resourceid, ?)', [params.tablename, params.selectedids.concat(params.unselectedids).join(',')]).transacting(trx)); //抽查通过 */
                            }
                            return Promise.all(promiseArray);
                        })
                    ])
                    .then(trx.commit)
                    .catch(trx.rollback);
            }).then(function (trx) {
                resolve(trx);
            }).catch(function (err) {
                console.error(err);
                reject(err);
            });
        });
    },
    //数据筛选 检查  数据获取
    gettaskitem_inspect: function (params) {
        return new Promise(function (resolve, reject) {
            var number = params.tasknumber;
            // 事务模式
            knex.transaction(function (trx) {
                if (params.tag == '') {
                    return Promise.all([
                            knex.raw('select count(1) as totalcount from ?? where status=3 and userid=?', [params.tablename, params.userid]).transacting(trx).then(function (data) {
                                console.log(data);
                                var rows = data[0][0].totalcount;
                                return Promise.all([
                                    knex.raw('update ?? a INNER JOIN (select resourceid from ?? where status=2  ORDER BY rand() limit ?) b on a.resourceid=b.resourceid set a.userid=?,status=3;', [params.tablename, params.tablename, rows > number ? 0 : Math.abs(number - rows), params.userid]).transacting(trx), //分配任务
                                    knex.raw('select a.*,a.label,b.tasktags  from ?? a  LEFT JOIN tasklist b on b.dsid=?  where a.status=3 and a.userid=? limit ?', [params.tablename, params.dsid, params.userid, number]).transacting(trx) //返回任务
                                ]);
                            })
                        ])
                        .then(trx.commit)
                        .catch(trx.rollback);
                } else {
                    return Promise.all([
                            knex.raw("select count(1) as totalcount from ?? where status=3 and userid=? and JSON_SEARCH(label->'$.outputs[*].name','one',?) is not null", [params.tablename, params.userid, params.tag]).transacting(trx).then(function (data) {
                                console.log(data);
                                var rows = data[0][0].totalcount;
                                return Promise.all([
                                    knex.raw("update ?? a INNER JOIN (select resourceid from ?? where status=2  and JSON_SEARCH(label->'$.outputs[*].name','one',?) is not null  ORDER BY rand() limit ?) b on a.resourceid=b.resourceid set a.userid=?,status=3;", [params.tablename, params.tablename, params.tag, rows > number ? 0 : Math.abs(number - rows), params.userid]).transacting(trx), //分配任务
                                    knex.raw("select a.*,a.label,b.tasktags  from ?? a  LEFT JOIN tasklist b on b.dsid=?  where a.status=3 and a.userid=?  and JSON_SEARCH(a.label->'$.outputs[*].name','one',?) is not null  limit ?", [params.tablename, params.dsid, params.userid, params.tag, number]).transacting(trx) //返回任务
                                ]);
                            })
                        ])
                        .then(trx.commit)
                        .catch(trx.rollback);
                }
            }).then(function (trx) {
                resolve(trx);
            }).catch(function (err) {
                console.error(err);
                reject(err);
            });
        });
    },
    //数据筛选 抽查  数据获取
    gettaskitem_rndinspect: function (params) {
        return new Promise(function (resolve, reject) {
            var number = params.tasknumber;
            // 事务模式
            knex.transaction(function (trx) {
                if (params.tag == '') {
                    return Promise.all([
                            knex.raw('select count(1) as totalcount from ?? where status=5 and userid=?', [params.tablename, params.userid]).transacting(trx).then(function (data) {
                                console.log(data);
                                var rows = data[0][0].totalcount;
                                return Promise.all([
                                    knex.raw('update ?? a INNER JOIN (select resourceid from ?? where status=4  ORDER BY rand() limit ?) b on a.resourceid=b.resourceid set a.userid=?,status=5;', [params.tablename, params.tablename, rows > number ? 0 : Math.abs(number - rows), params.userid]).transacting(trx), //分配任务
                                    /*  knex.raw('select a.*,a.label from ?? a where a.status=5 and a.userid=? limit ?', [params.tablename, params.userid, number]).transacting(trx), //返回任务 */
                                    knex.raw('select a.*,a.label,b.tasktags  from ?? a  LEFT JOIN tasklist b on b.dsid=?  where a.status=5 and a.userid=? limit ?', [params.tablename, params.dsid, params.userid, number]).transacting(trx), //返回任务
                                    knex.raw('SELECT (select count(1) from ?? where status=6)/(select count(1) from ??) as percent', [params.tablename, params.tablename]).transacting(trx) //抽查进度
                                ]);
                            })
                        ])
                        .then(trx.commit)
                        .catch(trx.rollback);
                } else {
                    return Promise.all([
                            knex.raw("select count(1) as totalcount from ?? where status=5 and userid=? and JSON_SEARCH(label->'$.outputs[*].name','one',?) is not null", [params.tablename, params.userid, params.tag]).transacting(trx).then(function (data) {
                                console.log(data);
                                var rows = data[0][0].totalcount;
                                return Promise.all([
                                    knex.raw("update ?? a INNER JOIN (select resourceid from ?? where status=4 and JSON_SEARCH(label->'$.outputs[*].name','one',?) is not null  ORDER BY rand() limit ?) b on a.resourceid=b.resourceid set a.userid=?,status=5;", [params.tablename, params.tablename, params.tag, rows > number ? 0 : Math.abs(number - rows), params.userid]).transacting(trx), //分配任务
                                    /*  knex.raw('select a.*,a.label from ?? a where a.status=5 and a.userid=? limit ?', [params.tablename, params.userid, number]).transacting(trx), //返回任务 */
                                    knex.raw("select a.*,a.label,b.tasktags  from ?? a  LEFT JOIN tasklist b on b.dsid=?  where a.status=5 and a.userid=?  and JSON_SEARCH(label->'$.outputs[*].name','one',?) is not null limit ?", [params.tablename, params.dsid, params.userid, params.tag, number]).transacting(trx), //返回任务
                                    knex.raw('SELECT (select count(1) from ?? where status=6)/(select count(1) from ??) as percent', [params.tablename, params.tablename]).transacting(trx) //抽查进度
                                ]);
                            })
                        ])
                        .then(trx.commit)
                        .catch(trx.rollback);
                }
            }).then(function (trx) {
                resolve(trx);
            }).catch(function (err) {
                console.error(err);
                reject(err);
            });
        });
    }
};